// pages/input_information/index.js
const app = getApp()
import {
  uploadFile
} from '../../api/common.js'
import {
  qualificateApply,
  qualificateApplyDetail
} from '../../api/qualificate.js'
import { deepClone } from '../../utils/deepClone.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasSkuQualificate: '', 
   // "hasSkuQualificate"//0：表示需要先申请资质，1：表示在当前组别中，该参赛者可以直接参与，2:表示失败,3：表示该参赛者已提交资质，还未审核成功，提交订单需要携带applyId  8(需要额外填写表单)/9（未认证通过且需要额外填写表单）:已经填过，还没提交（自定义）
    qualificateIds: '',
    applyId: '',
    userName: '', // 用户名称
    count: 3, // 图片总数
    imageList: [], // 图片
    imgUrl: [], // 保存后的图片地址
    title: '', // 需要认证指定资质的名称
    remark:'',
    send: false,
    failDesc: '', //失败原因
    matchFormList:[],//需要填写的动态表单列表
    changeDataNow:false,//用来存储数据是否在修改状态，避免修改未结束确认按钮就已点击造成验证出错


    oldHasSkuQualificate:0 //旧资质
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.barTitle) { //有携带title属性
      wx.setNavigationBarTitle({
        title: options.barTitle
      })
    }
    this.setData({
      title: options.title,
      userName: options.userName,
      userId: options.uid,
      hasSkuQualificate: options.hasSkuQualificate,
      pid: options.pid
    })
    if (options.arr) {
      this.setData({
        imgUrl: JSON.parse(options.arr)
      })
    }
    if (options.qualificateIds) {
      this.setData({qualificateIds: options.qualificateIds})
    }
    if (options.remark) {
      this.setData({remark: options.remark})
    }
    if (options.applyId) {
      this.setData({
        applyId: options.applyId
      })
      this._qualificateApplyDetail(options.applyId)
    }

    if (options.hasOwnProperty('type')) { //需要当前页提交 我的--页面进去的
      this.setData({
        send: options.hasOwnProperty('type')
      })
    }
    if (options.hasOwnProperty('oldHasSkuQualificate')&&options.oldHasSkuQualificate!=0) { //有旧资质的
      console.log('资质被改')
      this.setData({
        oldHasSkuQualificate: 1
      })
    }
    
    let pages = getCurrentPages();
    this.prevPage = pages[pages.length - 2]; // 上个页面
  },
  onShow() {
    if (this.data.send) {//单页面进入
    } else { // 详情页进入
      let { matchSkuList, select, bindIndex } = this.prevPage.data
      if (matchSkuList[select].matchSkuFormList.length>0) {//是否需要填写其它项
        let u = matchSkuList[select].selectedUser[bindIndex] // 当前用户数据
        this.setData({ matchFormList: deepClone(u.hasOwnProperty('matchFormList') ? u.matchFormList : matchSkuList[select].matchSkuFormList) })
        //如果没有设置过用户填写项则为默认数据，否则为用户填写的数据
      }
    }
  },
  _qualificateApplyDetail(id){
    qualificateApplyDetail(id).then(res=>{
      this.setData({ hasSkuQualificate: res.data.status, failDesc: res.data.failDesc })
    })
  },
  chooseImage(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.src, // 当前显示图片的http链接  
      urls: this.data.imgUrl // 需要预览的图片http链接列表  
    })
  },
  addImage() { // 选择图片
    let _this = this;
    let {count,imageList} = this.data
    wx.chooseImage({
      count: count - imageList.length, // 可用数-当前数
      success: res => {
        _this.setData({
          imageList: [...imageList, ...res.tempFilePaths]
        })
        res.tempFilePaths.forEach(e => {
          _this._uploadFile(e)
        })
      }
    })
  },
  // 文件上传
  _uploadFile(img) {
    uploadFile(img, 'file', res => { // 图片上传成功
      res.data = JSON.parse(res.data)
      if (res.data.code != 0) {
        this.showToast('图片上传失败', 'none')
      } else {
        this.setData({
          ['imgUrl[' + this.data.imgUrl.length + ']']: res.data.url
        })
      }
      this.check()
    }, err => { // 图片上传失败
      this.showToast('图片上传失败', 'none')
      this.check()
    })
  },
  getCompData(e) { //获取子组件设置的值
    this.setData({ changeDataNow:true,['matchFormList[' + e.detail.formIndex + ']']: e.detail.inputObj})
    let { matchSkuList, select, bindIndex } = this.prevPage.data
    let { matchFormList } = this.data
    let obj = matchSkuList[select].selectedUser[bindIndex]
    if (matchFormList != '') { // 需要有动态表单项，则提交
      obj.matchFormList = matchFormList
    }
    this.prevPage.setData({ ['matchSkuList[' + select + '].selectedUser[' + bindIndex + ']']: obj })
    // setTimeout(()=>{ 
      this.setData({ changeDataNow: false })
    // },1000)
  },
  delImage(e) { // 删除图片
    let index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '删除图片',
      content: '确定要删除第' + Number(index + 1) + '张图片？',
      showCancel: true, //是否显示取消按钮
      cancelText: "否", //默认是“取消”
      cancelColor: '#1781FF', //取消文字的颜色
      confirmText: "是", //默认是“确定”
      confirmColor: '#1781FF', //确定文字的颜色
      success: res => {
        if (!res.cancel) {
          //点击确定
          let {imageList,imgUrl} = this.data
          imageList.splice(index, 1)
          imgUrl.splice(index, 1)
          this.setData({
            imageList,
            imgUrl
          })
        }
      }
    })
  },

  //数据验证
  check() {
    let { imgUrl} = this.data
    if (imgUrl.length <= 0) {
      this.setData({
        sendState: 2
      })
    } else {
      this.setData({
        sendState: 0
      })
    }
  },

  //提交认证信息
  toSend() {
    setTimeout(()=>{
      let { send, imgUrl, changeDataNow,hasSkuQualificate} = this.data;
      let message={title:'',icon:'none'}
      if (send) { // 需要当前页提交
        if (imgUrl.length == 0) {
          message.title='请至少上传1张图片'
        } else {
          let { applyId, pid, imgUrl, qualificateIds } = this.data;
          let obj = {
            participantId: pid,
            qualificateId: qualificateIds,
            imageList: imgUrl
          }
          if (applyId != '') {
            obj.applyId = applyId
          }
          qualificateApply(obj).then(res => {
            if (res.code == 0) {
              message.title = '已提交'
              message.icon = 'success'
              setTimeout(() => {
                if (qualificateIds == '') {
                  wx.navigateTo({ url: '/pages/state_page/index?pid=' + pid })
                } else {
                  wx.navigateBack()
                }
              }, 2000)
            } else {
              message.title = res.msg
            }
          })
        }
      } else {// 不需要当前页提交，直接将数据保存到上个页面
        if(!changeDataNow){//数据修改完成
          let { matchSkuList, select, bindIndex } = this.prevPage.data
          let { matchFormList, imgUrl } = this.data
          let errTitle = '';
          let hasAns = false; // 表单是否有没有填的项
          let firstAns = true; // 表单是否有没有填的项第一个判断，避免重置了上面的hasAns
          if(matchFormList.length>0){
            matchFormList.forEach((e, i) => {
              if (errTitle == '') { //不管是不是必填都验证
                let { formType, required, value, title, minLength, maxLength, optionList } = e;
                  switch (formType) {
                    case "input":
                    case "textarea":
                      if(value != ''){
                        if (minLength > 0 && value.length < minLength) {
                          errTitle = title + '长度不能少于' + minLength + '位'
                        } else if (maxLength > 0 && value.length > maxLength) {
                          errTitle = title + '长度不能多于' + maxLength + '位'
                        }
                      }else if(required==1){
                        errTitle = '请输入' + title
                      }else if(required==2&&firstAns){//非必填项
                        hasAns = true;
                        firstAns=false;
                      }
                      this.setData({ ['matchFormList[' + i + '].errTitle']: errTitle })
                      break;
                    case "select": // 下拉列表
                    case "checkbox": // 复选框
                    case "radio": // 单选框
                      let num = 0
                      optionList.forEach(eu => {
                        if (eu.status == '1') {
                          num++
                        }
                      })
                      if(num == 0&&required==1){ // 必填
                        this.setData({ ['matchFormList[' + i + '].errTitle']: '请选择' + title })
                        errTitle = '请选择' + title
                      }else if(required==2&&firstAns){//非必填项
                        hasAns = true;
                        firstAns=false;
                      }
                      break;
                    case "input_att": //图片上传
                      if (required==1) { // 必填
                        if(value.length == 0){
                          this.setData({ ['matchFormList[' + i + '].errTitle']: '请上传' + title })
                          errTitle = '请上传' + title;
                        }
                      }else if(required==2&&firstAns){//非必填项
                        hasAns = true;
                        firstAns=false;
                      }
                      break;
                    default:
                      break;
                  }
              } else {
                this.setData({ ['matchFormList[' + i + '].errTitle']: '' })
              }
            })
          }
          if (errTitle == '') {//动态表单数据没有出错
            console.log(hasSkuQualificate)
            if (imgUrl.length == 0 && (hasSkuQualificate != 1&&hasSkuQualificate != 8)) {//没有上传图片
              message.title = '请至少上传1张图片'
            } else {
              let obj = matchSkuList[select].selectedUser[bindIndex];
              if(hasAns){ //有未填项
                if(obj.hasOwnProperty('oldHasSkuQualificate')){//有设置过
                  obj.hasSkuQualificate = obj.oldHasSkuQualificate
                }
              }else{
                if(!obj.hasOwnProperty('oldHasSkuQualificate')){//没有设置过
                  obj.oldHasSkuQualificate = obj.hasSkuQualificate
                }
              }
              obj.hasSkuQualificate = (obj.hasSkuQualificate == 1 || obj.hasSkuQualificate == 8)?8:9;
              obj.arr = imgUrl
              if (matchFormList != '') { // 需要有动态表单项，则提交
                obj.matchFormList = matchFormList
              }
              console.log(obj)
              this.prevPage.setData({ ['matchSkuList[' + select + '].selectedUser[' + bindIndex + ']']: obj })
              wx.navigateBack(1)
            }
          } else {
            message.title = errTitle
          }
        }
      }
      if (message.title != ''){
        wx.showToast(message)
      }

    },500)
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})